package com.zeny.xdclass.utils;

import com.zeny.xdclass.domain.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @ClassName JwtUtils
 * @Description TODO
 * @Author zeny
 */
public class JwtUtils {

    public static final String SUBJECT = "xdclass";

    public static final Long EXPIRE = 1000 * 60 * 60 * 24 * 7L; //过期时间

    public static final String APPSECRET = "zeny";

    public static String genJsonWebToken(User user) {
        if (user == null
                || user.getId() == null
                || StringUtils.isEmpty(user.getName())
                || StringUtils.isEmpty(user.getHeadImg())) {
            return null;
        }
        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("id", user.getId())
                .claim("name", user.getName())
                .claim("img", user.getHeadImg())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, APPSECRET)
                .compact();
        return token;
    }


    public static Claims checkToken(String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        try {
            Claims claims = Jwts.parser().setSigningKey(APPSECRET).parseClaimsJws(token).getBody();
            return claims;
        } catch (Exception e) {

        }
        return null;
    }

    public static void main(String[] args) {
        User user = new User();
        user.setId(1);
        user.setName("zeny");
        user.setHeadImg("zeny.com");
        String token = genJsonWebToken(user);
        System.out.println(token);
        Claims claims = checkToken(token);
        System.out.println(claims);
    }

}
